package FileMnitor;

import cn.hutool.core.io.watch.WatchMonitor;
import cn.hutool.core.io.watch.Watcher;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.util.StringUtils;

import java.io.File;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.WatchEvent;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author LHB
 * @date 2019/11/19 16:08
 * 文件监听工具类
 */
public class FlieMonitor {

    /**
     * 新建文件存放队列
     */
    public static LinkedBlockingDeque<File> createFileQueue = new LinkedBlockingDeque<>();
    /**
     * 更新文件存放队列
     */
    public static LinkedBlockingDeque<File> modifyFileQueue = new LinkedBlockingDeque<>();


    /**
     * 初始化启动监听器
     *
     * @param monitorPath
     */
    public WatchMonitor monitorInit(String monitorPath) {
        if (StringUtils.isEmpty(monitorPath)) {
            return null;
        }
        WatchMonitor watchMonitor = WatchMonitor.create(monitorPath, WatchMonitor.ENTRY_CREATE);
        watchMonitor.setWatcher(new Watcher() {
            @Override
            public void onCreate(WatchEvent<?> event, Path currentPath) {
                String filepath = Paths.get(currentPath.toString(), event.context().toString()).toString();
                File file = new File(filepath);

                createFileQueue.offer(file);
            }

            @Override
            public void onModify(WatchEvent<?> event, Path currentPath) {
                String filepath = Paths.get(currentPath.toString(), event.context().toString()).toString();
                File file = new File(filepath);
                modifyFileQueue.offer(file);
            }

            @Override
            public void onDelete(WatchEvent<?> event, Path currentPath) {

            }

            @Override
            public void onOverflow(WatchEvent<?> event, Path currentPath) {

            }
        });
        return watchMonitor;
    }


    /**
     * remove   移除并返回队列头部的元素     如果队列为空，则抛出一个NoSuchElementException异常
     * element  返回队列头部的元素              如果队列为空，则抛出一个NoSuchElementException异常
     * offer       添加一个元素并返回true        如果队列已满，则返回false
     * poll         移除并返问队列头部的元素     如果队列为空，则返回null
     * peek       返回队列头部的元素              如果队列为空，则返回null
     * put         添加一个元素                       如果队列满，则阻塞
     * take        移除并返回队列头部的元素    
     *
     */

}
